import React, { useMemo, useState } from 'react';
import {
  Card,
  Form,
  Input,
  Select,
  Button,
  Space,
  Table,
  Tag,
  Modal,
  InputNumber,
  message,
} from 'antd';

// 提现记录页面（模仿 admin-web/src/views/order/WithdrawalRecord.vue 的结构与交互）
// 功能：查询、列表、确认提现（密码）与撤销

const statusMap = {
  0: { text: '待确认', color: 'gold' },
  1: { text: '已完成', color: 'green' },
  2: { text: '财务取消', color: 'red' },
  3: { text: '已取消', color: 'default' },
};

const mockData = [
  {
    id: 201,
    userName: 'alice',
    payeeName: 'Alice',
    bankName: '中国银行',
    bankAccount: '6222 8888 0000 1234',
    price: 1200,
    createTime: '2024-09-05 11:20:00',
    withdrawalStatus: 0,
  },
  {
    id: 202,
    userName: 'bob',
    payeeName: 'Bob',
    bankName: '招商银行',
    bankAccount: '6225 1111 2222 3333',
    price: 500,
    createTime: '2024-09-06 14:05:00',
    withdrawalStatus: 1,
  },
  {
    id: 203,
    userName: 'carol',
    payeeName: 'Carol',
    bankName: '建设银行',
    bankAccount: '6227 7777 8888 9999',
    price: 3000,
    createTime: '2024-09-07 09:42:00',
    withdrawalStatus: 2,
  },
];

const WithdrawalRecord = () => {
  const [form] = Form.useForm();
  const [dataSource, setDataSource] = useState(mockData);
  const [pwdVisible, setPwdVisible] = useState(false);
  const [currentRow, setCurrentRow] = useState(null);
  const [password, setPassword] = useState('');

  const onSearch = () => {
    const values = form.getFieldsValue();
    const { userName, withdrawalStatus } = values;
    const filtered = mockData.filter((item) => {
      const conds = [
        !userName || String(item.userName).includes(userName),
        withdrawalStatus === undefined || withdrawalStatus === '' || String(item.withdrawalStatus) === String(withdrawalStatus),
      ];
      return conds.every(Boolean);
    });
    setDataSource(filtered);
  };

  const onReset = () => {
    form.resetFields();
    setDataSource(mockData);
  };

  const onConfirm = (row) => {
    setCurrentRow(row);
    setPassword('');
    setPwdVisible(true);
  };

  const doConfirm = () => {
    if (!password) {
      message.warning('请输入财务确认密码');
      return;
    }
    if (!currentRow) return;
    message.success(`提现确认成功：${currentRow.userName}`);
    setPwdVisible(false);
    setDataSource((prev) => prev.map((r) => (r.id === currentRow.id ? { ...r, withdrawalStatus: 1 } : r)));
  };

  const onRevoke = (row) => {
    message.success(`已撤销提现：${row.userName}`);
    setDataSource((prev) => prev.map((r) => (r.id === row.id ? { ...r, withdrawalStatus: 3 } : r)));
  };

  const columns = useMemo(
    () => [
      { title: '用户名', dataIndex: 'userName', key: 'userName' },
      { title: '收款人', dataIndex: 'payeeName', key: 'payeeName' },
      { title: '银行', dataIndex: 'bankName', key: 'bankName' },
      { title: '银行卡号', dataIndex: 'bankAccount', key: 'bankAccount' },
      {
        title: '金额',
        dataIndex: 'price',
        key: 'price',
        render: (v) => `${v}`,
      },
      { title: '创建时间', dataIndex: 'createTime', key: 'createTime' },
      {
        title: '状态',
        dataIndex: 'withdrawalStatus',
        key: 'withdrawalStatus',
        render: (st) => {
          const cfg = statusMap[st] || { text: st, color: 'default' };
          return <Tag color={cfg.color}>{cfg.text}</Tag>;
        },
      },
      {
        title: '操作',
        key: 'action',
        render: (_, row) => (
          <Space>
            {row.withdrawalStatus === 0 && (
              <Button type="primary" onClick={() => onConfirm(row)}>
                确认提现
              </Button>
            )}
            {row.withdrawalStatus === 0 && (
              <Button danger onClick={() => onRevoke(row)}>
                撤销
              </Button>
            )}
          </Space>
        ),
      },
    ],
    []
  );

  return (
    <Card title="提现记录">
      <Form form={form} layout="inline" style={{ marginBottom: 12 }}>
        <Form.Item label="用户名" name="userName">
          <Input allowClear placeholder="输入用户名" />
        </Form.Item>
        <Form.Item label="提现状态" name="withdrawalStatus">
          <Select allowClear style={{ width: 140 }} placeholder="选择状态">
            <Select.Option value={0}>待确认</Select.Option>
            <Select.Option value={1}>已完成</Select.Option>
            <Select.Option value={2}>财务取消</Select.Option>
            <Select.Option value={3}>已取消</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" onClick={onSearch}>
              查询
            </Button>
            <Button onClick={onReset}>重置</Button>
          </Space>
        </Form.Item>
      </Form>

      <Table rowKey="id" columns={columns} dataSource={dataSource} pagination={{ pageSize: 10 }} />

      <Modal
        title="财务确认"
        open={pwdVisible}
        onCancel={() => setPwdVisible(false)}
        onOk={doConfirm}
        okText="确认"
        cancelText="取消"
      >
        <Form layout="vertical">
          <Form.Item label="确认密码">
            <Input.Password
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="请输入财务确认密码"
            />
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  );
};

export default WithdrawalRecord;